import subprocess
import time

# 需要在PATH变量中添加adb路径
# def addExecPath(addpath):
#     envpath = os.getenv('PATH')
#     execpath = os.path.abspath(addpath)
#     os.putenv('PATH', execpath+";"+envpath)

# addExecPath(os.path.dirname(sys.argv[0])+os.sep+"..\\bin")

def isAdbAlive():
    cmd = "tasklist"
    s = subprocess.check_output(cmd, encoding="gb2312")
    for i in s.splitlines():
        if i.startswith("adb.exe"):
            return True
    return False

def chk_status(kill_adb=False):
    if not isAdbAlive(): subprocess.getoutput("adb start-server") # 启动adb服务
    st_list = ['device', 'recovery', 'rescue', 'sideload', 'bootloader', 'disconnect']
    fb_list = ['fastboot']
    status = subprocess.getstatusoutput("adb get-state")
    if status[0] == 0:
        for i in st_list:
            if status[1].strip(' ') == i:
                return i
    else:
        status2 = subprocess.getoutput("fastboot devices")
        if not status2.strip(' ')=='':
            return fb_list[0]
    return False
    if kill_adb:
        subprocess.getoutput("adb kill-server")

def loopUntil(state, maxretries=20, waitretries=1):
    for i in range(maxretries):
        if chk_status() == state:
            return True
        time.sleep(waitretries)
    if chk_status() == state:
        return True
    else:
        return False

def getFastbootPartitionName():
    s = subprocess.getoutput("fastboot getvar all")
    part = []
    for i in s.splitlines():
        if len(i.split(" "))>1:
            if i.split(" ")[1].split(":")[0].startswith("partition-type"):
                part.append(i.split(" ")[1].split(":")[1])
    return part